package zhtt.redis.utils;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.List;

public class JsonUtils {

    public static String toJson(Object obj){
        Gson gson = new Gson();
        return gson.toJson(obj);
    }

    public static <T> T toObject(String jsonStr, Class<T> clazz) {
        if (jsonStr == null) {
            return null;
        }
        Gson gson = new Gson();
        T readValue = gson.fromJson(jsonStr,clazz);
        return readValue;
    }

    public static<T> List<T> toObjList(String json, Class<T> clazz){
        if(json==null||json.length()==0){
            return null;
        }else {
            json=json.trim();
            if(json.startsWith("[")==false||json.endsWith("]")==false){
                return null;
            }
        }
        Gson gson = new Gson();
        List<T> objList = gson.fromJson(json, new TypeToken<List<T>>(){}.getType());
        return objList;
    }
}
